﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using MindFusion.Diagramming;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;
using TaleGeneratorModel;


namespace Inference
{
    public partial class ReasonForm : Form
    {

        TaleClasses Tale;

        public ReasonForm(TaleClasses _tale)
        {
            InitializeComponent();
            Tale = _tale;
        }


        List<TreeNode> GetNodes(string name)
        {
            List<TreeNode> nodes = new List<TreeNode>();
                var Sl = from f in Tale.GetViewSlotValues()
                         orderby f.Number
                         where f.FrameName.ToLower().Trim() == name.ToLower().Trim() && f.Number!=0
                         select f;
                foreach (var s in Sl)
                {

                    TreeNode node=new TreeNode("'" + s.Name + "' : '" + s.Value + "'");
                    if (Tale.Frame.Where(f => f.Name.ToLower().Trim() == s.Value.ToLower().Trim()).Count() > 0) // если  субфрейм
                        node.Nodes.AddRange(GetNodes(s.Value).ToArray());
                    nodes.Add(node);
                }
            return nodes;
        }


        int GetLastIndex(string FrameID)
        {
            int index=-1;
            for (int i = 0; i < TreeRules.Nodes["root"].Nodes.Count; i++)
                if (TreeRules.Nodes["root"].Nodes[i].ImageKey == FrameID)
                    index = i;
                return index;
        }

        void ClearTreeFromEntities()
        {
            TreeNode Root=TreeRules.Nodes["root"];
            for (int i = Root.Nodes.Count - 1; i >= 0; i--)
            {
                int key= int.Parse(Root.Nodes[i].ImageKey);
                int valueid=Tale.GetViewFrameExample().Where(f=>f.ID==key).First().ValueID;
                if (Tale.DomainValueM2M.Where(d => d.Value == valueid).First().Domain == 1)
                    Root.Nodes[i].Remove();
            }
        }

        bool  IsSituation(int FrameID)
        {
            Frame fr;
            long ID = FrameID;
            do
            {
                fr = Tale.Frame.Where(f => f.Id == ID).First();
                if (fr.Is_a.HasValue)
                    ID = fr.Is_a.Value;
                else
                    ID = 0;
            }
            while (ID != 0);
            if (fr.Name.ToLower() == "ситуация")
                return true;
            else
                return false;
        }

        private void ReasonForm_Load(object sender, EventArgs e)
        {
            // заполнение списка фреймов
            var Frames = from s in Tale.Log where s.Slot.SlotPosition != 0 select s;
            long FrameID = 0;
            bool test = true;
            bool IsFrame = true;
            TreeNode Root = TreeRules.Nodes["root"];

            foreach (var row in Frames)
            {
                //string val = Tale.GetViewSlotValues().Where(d => d.ID == row.ValueId).First().Value;
                string val = Tale.GetViewSlotValues().Where(d => d.ValueID == row.ValueId).First().Value;
                TreeNode node; TreeNode Fnode;
                IsFrame = Tale.DomainValueM2M.Where(v => v.Id == row.ValueId).First().Domain ==  7; // Рефакторинг
                if (IsFrame) // если ситуация
                {
                    if (FrameID == row.Slot.FrameFrame.Id)
                        test = true;
                    else
                        test = false;
                    FrameID = row.Slot.FrameFrame.Id;
                }
                if (Root.Nodes.ContainsKey(row.Slot.Frame.ToString()) && test)
                {
                   // node = Root.Nodes[Root.Nodes.IndexOfKey(row.Slot.FrameID.ToString())].Nodes.Add("'" + row.Slot.Name + "' : '" + val + "'");
                    node = Root.Nodes[GetLastIndex(row.Slot.Frame.ToString())].Nodes.Add("'" + row.Slot.Name + "' : '" + val + "'");
                }
                else
                {
                    if ((!test && Root.Nodes.ContainsKey(row.Slot.Frame.ToString()))
                        //&& !frame)
                        && Root.Nodes[GetLastIndex((row.Slot.Frame.ToString()))].ForeColor != Color.Red)
                    {
                        Fnode = Root.Nodes[GetLastIndex((row.Slot.Frame.ToString()))]; // для изменения состояния(например)
                    }
                    else
                    {
                        // добавляем в корень
                        Fnode = Root.Nodes.Add(row.Slot.Frame.ToString(), row.Slot.FrameFrame.Name, row.Slot.Frame.ToString());
                        FontFamily ff = FontFamily.GenericSerif; //Families[237];
                        Font F = new Font(ff, 10, FontStyle.Bold);
                        if (FrameID == row.Slot.FrameFrame.Id)
                            //Fnode.ForeColor = Color.MediumSeaGreen;
                            Fnode.NodeFont = F;
                    }
                    node = Fnode.Nodes.Add("'" + row.Slot.Name + "' : '" + val + "'");
                }
                    long fid = 0;
                    if (Tale.Frame.Where(f => f.Name.ToLower().Trim() == val.ToLower().Trim()).Count() > 0)
                        fid = Tale.Frame.Where(f => f.Name.ToLower().Trim() == val.ToLower().Trim()).First().Id;                   
                    //// перетягиваем сущность к ситуации
                    if (Root.Nodes.ContainsKey(fid.ToString()))
                    {
                        TreeNode rnode = (TreeNode)Root.Nodes[fid.ToString()].Clone();
                        //TreeRules.Nodes["root"].Nodes[fid.ToString()].Remove();
                        node.Nodes.AddRange(rnode.Nodes.Cast<TreeNode>().ToArray());
                    }
                    else
                    { 
                    }
                

                if (row.Success)
                {
                    node.Parent.ForeColor = Color.Green;
                }
                else
                {
                    node.ForeColor = Color.Red;
                    node.Parent.ForeColor = Color.Red;
                }
              
            }
            ClearTreeFromEntities();
            TreeRules.Nodes["root"].Expand();

            // заполнение списка фреймов-экземпляров
            //var FramesID = from s in Tale.ViewValues select s.FrameID;
            List<int> FramesID=new List<int>();
            foreach (ViewValues val in Tale.GetViewSlotValues())
            {
                if (FramesID.Contains(val.FrameID))
                    FramesID.Remove(val.FrameID);
                FramesID.Add(val.FrameID);
            }

            foreach(var id in FramesID)
            {
                TreeNode node = TreeChain.Nodes["root"].Nodes.Add(Tale.Frame.Where(f=>f.Id==id).First().Name);
                FontFamily ff = FontFamily.GenericSerif; //Families[237];
                Font F = new Font(ff, 10, FontStyle.Bold);
                //node.ForeColor=Color.Green;
                node.NodeFont = F;
                var Slots = from f in Tale.GetViewSlotValues() orderby f.Number where f.FrameID==id && f.Number!=0 select f;
                foreach (var Slot in Slots)
                {
                    TreeNode SubNode = node.Nodes.Add("'" + Slot.Name + "' : '" + Slot.Value + "'");
                    if (Tale.Frame.Where(f => f.Name.ToLower().Trim() == Slot.Value.ToLower().Trim()).Count() > 0) // если  субфрейм
                        SubNode.Nodes.AddRange(GetNodes(Slot.Value).ToArray());
                }
                
            }
            TreeChain.Nodes["root"].Expand();

            // генерация текста            
            //foreach (var id in FramesID)
            //    if (IsSituation(id)) // если ситуация
            //    {
            //        long fid=id;
            //        while(Tale.Pattern.Where(p=>p.FrameID==fid).Count()==0) // поиск фрейма с заданным шаблоном
            //            fid= Tale.Frames.Where(f => f.ID == fid).First().Is_a.Value;

            //        var Pats = from f in Tale.Pattern orderby f.Number where f.FrameID == fid select f;
            //        foreach (Pattern pat in Pats)
            //        {
            //            string SlotName = pat.Slot.Name;
            //            string AddedText = Tale.ViewValues.Where(v => v.FrameID == id && v.Name == SlotName).First().Value;
            //            AddedText= AddedText.Replace(' ','_');
            //            if (pat.Number == 0)
            //                GeneratedText.AppendText(" " +AddedText);
            //            else
            //                GeneratedText.AppendText (" " +AddedText.ToLower() );
            //        }
            //        GeneratedText.AppendText(".\n");
            //    }

        }

        void TreeChain_ClientSizeChanged(object sender, EventArgs e)
        {
            button3.Location = new Point(TreeChain.ClientSize.Width - 40, button3.Location.Y);
            button4.Location = new Point(TreeChain.ClientSize.Width - 40, button4.Location.Y);
        }

        void TreeRules_ClientSizeChanged(object sender, EventArgs e)
        {
            button1.Location = new Point(TreeRules.ClientSize.Width - 40, button1.Location.Y);
            button2.Location = new Point(TreeRules.ClientSize.Width - 40, button2.Location.Y);
        }
        
        private void button2_Click_1(object sender, EventArgs e)
        {
            if (TreeRules.SelectedNode != null)
            {
                TreeRules.SelectedNode.Collapse();
                if (TreeRules.SelectedNode == TreeRules.Nodes["root"])
                    TreeRules.SelectedNode.Expand();
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (TreeRules.SelectedNode != null)
            TreeRules.SelectedNode.ExpandAll();
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            if (TreeChain.SelectedNode != null)
            TreeChain.SelectedNode.ExpandAll();
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            if (TreeChain.SelectedNode != null)
            {
                TreeChain.SelectedNode.Collapse();
                if (TreeChain.SelectedNode == TreeChain.Nodes["root"])
                    TreeChain.SelectedNode.Expand();
            }
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BtnSaveText_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "Обычный текст (*.txt)|*.txt";
            saveFileDialog1.Filter += "|Документ Word(*.docx)|*.docx";
            saveFileDialog1.Filter += "|Документ Word 97-2003 (*.doc)|*.doc";
            saveFileDialog1.FileName = "";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamWriter writer = new StreamWriter(saveFileDialog1.FileName);
                writer.Write(GeneratedText.Text);
                writer.Close();
            }
        }



    }
}
